/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package agents.communitymanager;

import BESA.ExceptionBESA;
import BESA.Kernell.Agent.Event.EventBESA;
import BESA.Kernell.Agent.KernellAgentExceptionBESA;
import BESA.Kernell.Agent.StateBESA;
import BESA.Kernell.System.Directory.AgHandlerBESA;
import co.edu.javeriana.ayllu.agents.communityagent.CommunityAgent;
import co.edu.javeriana.ayllu.agents.communityagent.CommunityAgentState;
import co.edu.javeriana.ayllu.agents.communitymanageragent.CommunityManagerAgent;
import co.edu.javeriana.ayllu.agents.interfaceagentagent.InterfaceAgent;
import co.edu.javeriana.ayllu.agents.sessionmanageragent.SessionManagerAgent;
import co.edu.javeriana.ayllu.agents.sessionmanageragent.SessionManagerAgentState;
import agents.community.UpdateSynchInterfaceGuard;
import agents.interfaceagent.IA_SynchCommInterface;
import agents.interfaceagent.IA_SynchCommInterfaceState;
import co.edu.javeriana.ayllu.data.Ayllu_Data_Message;
import co.edu.javeriana.ayllu.data.Ayllu_EventTypes;
import co.edu.javeriana.ayllu.data.Ayllu_WallMessageData;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * CommunityManagerAgent that hanldes a synchronous communication
 *
 * @author Ayllu
 */
public class CMA_SynchronousComm extends CommunityManagerAgent {

    public CMA_SynchronousComm(String alias, StateBESA state, double passwd) throws KernellAgentExceptionBESA {
        super(alias, state, passwd);
    }

    @Override
    public void cmaInitService() {
        //estado con lista de handlers, si los CA ya estan creados, se crean nuevos CA con el SM de cada "viejo" CA
        //se inicia o bien con agentes de comunidad o bien con agentes de sesión
        this.getAdmLocal().addService("WallService");
        this.getAdmLocal().bindService(this.getAid(), "WallService");
        try {
            initiateSynchronousCommunication();
        } catch (Exception e) {
            Logger.getLogger(CMA_SynchronousComm.class.getName()).log(Level.SEVERE, null, e);
        }
    }

    private void initiateSynchronousCommunication() throws NotEnoughMembersException {
        CMA_SynchronousCommState synchstate = (CMA_SynchronousCommState) this.getState();
        List<AgHandlerBESA> membersList = synchstate.getMembersHandlers();
        if (membersList.size() < 2) {
            //not enough members, at least 2
            throw new NotEnoughMembersException();
        }
        for (AgHandlerBESA agHandler : membersList) {
            AgHandlerBESA smHandler = null;
            if (agHandler.getAg() instanceof CommunityAgent) {
                smHandler = ((CommunityAgentState) agHandler.getAg().getState()).getSessionManagerHandler();
            } else if (agHandler.getAg() instanceof SessionManagerAgent) {
                smHandler = agHandler;
            }
            if (smHandler != null) {
                SessionManagerAgentState smaState = (SessionManagerAgentState) smHandler.getAg().getState();
                CMA_SynchronousCommState cmastate = (CMA_SynchronousCommState) this.getState();
                IA_SynchCommInterfaceState iaState = new IA_SynchCommInterfaceState(smHandler); //TODO _Chat el factory se encarga de hacer esto!!!!
                IA_SynchCommInterface iface;
                try {
                    InterfaceAgent.prepareIntance();
                    iface = new IA_SynchCommInterface(smHandler.getAlias().split("_")[1], iaState, cmastate.getVolatileGroupPassword());
                    iface.start();
                    smaState.addInterfaceAgentHandler(this.getAdmLocal().getHandlerByAid(iface.getAid()));
                    //creando los agentes de comunidad
                    List<Class> communityGuards = new ArrayList<Class>();
                    communityGuards.add(UpdateSynchInterfaceGuard.class);
                    AgHandlerBESA createdCa = this.createCommunityAgent(smHandler.getAlias().split("_")[1], smHandler, communityGuards);
                    iaState.setCatoreply(createdCa);
                    //Message to start chat communication
                    Ayllu_Data_Message data = new Ayllu_Data_Message(Ayllu_EventTypes.DISPLAY, null, "Bienvenido!");
                    EventBESA firstEvent = new EventBESA(UpdateSynchInterfaceGuard.class.getName(), data);

                    createdCa.sendEvent(firstEvent);
                } catch (ExceptionBESA ex) {
                    Logger.getLogger(CMA_SynchronousComm.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    }
}
